/*
 * @Author: Wangtao
 * @Date: 2022-07-13 13:49:33
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-08-25 12:46:57
 */
/**
 * 权限相关状态管理
 */
import { defineStore } from 'pinia'

import { adminRoutes } from '@app/base/router/admin-route'

import router, { constantRoutes } from '@app/base/router'

import { customerServiceRoutes } from '@app/base/router/customer-serviceroute'

import { RouteRecordRaw } from 'vue-router'

const hasPermission = (roles: string[], route: any) => {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export const filterAsyncRoutes = (routes: any[], roles: string[]) => {
  const res: any[] = []
  routes.forEach((route) => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

export const PermissionModule = defineStore('permission', {
  state: () => {
    return {
      mockRoles: ['admin'],
      dynamicRoutes: [],
      isFilterRoute: false
    }
  },
  getters: {},
  actions: {
    GenerateRoutes (roles: string[]) {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = adminRoutes
      } else {
        console.log('设置客服工作台路由===============')
        accessedRoutes = customerServiceRoutes
      }
      console.log(accessedRoutes)
        ; (this.dynamicRoutes as Array<RouteRecordRaw>) = constantRoutes.concat(accessedRoutes)
    },
    setClientType (type: number) {
      if (type === 0) {
        this.GenerateRoutes(['admin'])
      } else {
        this.GenerateRoutes(['agents'])
      }
    },
    updateFilterState (state: boolean) {
      this.isFilterRoute = state
    },
    removeRoutes () {
      this.dynamicRoutes.forEach((item: any) => {
        console.log(item, 'iiiiiiiiiiiiiiiiiii')
        router.removeRoute(item.name)
      })
    }
  }
})
